﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using POSSystem.BLL;

namespace WebUI.EditPages
{
    public partial class EditUser : BasePage
    {
        POSSystem.BLL.Users user;
        int custID;
        string mode;

        protected void Page_Load(object sender, EventArgs e)
        {
            base.Page_Load(sender, e);

            if (Request.QueryString[KEY] == null)
            {
                CloseDlg(0);
                return;
            }

            if (Request.QueryString[MODE] == null)
            {
                CloseDlg(0);
                return;
            }

            mode = Request.QueryString[MODE];

            if (Request.QueryString[ID] == null && (mode == EDIT_MODE || mode == VIEW_MODE))
            {
                CloseDlg(0);
                return;
            }

            user = (POSSystem.BLL.Users)Session[Request.QueryString[KEY]];
            string oldFilter = user.Filter;

            custID = Request.QueryString[ID] != null ? int.Parse(Request.QueryString[ID]) : 0;
            if (mode != ADD_MODE)
                user.Filter = POSSystem.BLL.Users.ColumnNames.ID + "=" + custID.ToString();
            else
                btnSave.Enabled = false;
            if (!IsPostBack && user.RowCount > 0 && mode != ADD_MODE)
                LoadInfo();

            user.Filter = oldFilter;
        }

        public void btnSave_OnClick(Object sender, EventArgs e)
        {
            Save();
            ScriptManager.RegisterClientScriptBlock(this, typeof(Page), Guid.NewGuid().ToString(), String.Format("window.returnValue={0};", 1), true);
        }

        private bool Save()
        {
            string oldFilter = user.Filter;
            try
            {
                if (mode == ADD_MODE)
                {
                    if (POSSystem.BLL.Users.IsUserNameExist(editUser.UserName, -1))
                        throw new ApplicationException("Username has already existed.");
                    user.AddNew();
                    user.BranchID = Branches.CurrentBranchID;
                    user.Deleted = false;
                }
                else
                {
                    if (POSSystem.BLL.Users.IsUserNameExist(editUser.UserName, custID))
                        throw new ApplicationException("Username has already existed.");
                    user.Filter = POSSystem.BLL.Users.ColumnNames.ID + "=" + custID;
                }

                if (editUser.Role > 0)//when saving foreign key, remember to check condition or we may get confliction
                    user.RoleID = editUser.Role;
                user.LastModifiedByUser = SessionUser.ID;
                user.LastModifiedDate = DateTime.UtcNow.AddHours(SysVars.TimeZone);
                user.UserName = editUser.UserName;
                user.FullName = editUser.FullName;
                user.Address = editUser.Address;
                user.Phone = editUser.Phone;
                user.RoleName = editUser.RoleName;

                if(editUser.Password != user.Password)
                    user.Password = Utilities.CreateMD5Hash( editUser.Password);

                user.Save();
                user.Filter = oldFilter;
                ((Popup)Master).ShowMessage("Saved");
                return true;
            }
            catch (Exception ex)
            {
                user.RejectChanges();
                user.Filter = oldFilter;

                ((Popup)Master).ShowErrorMessage(ex.Message);
                ErrorLog.WriteToFile("editUser.aspx.cs", "Save", ex.StackTrace);
                return false;
            }
        }

        private void LoadInfo()
        {
            try
            {
                if (!user.IsColumnNull(POSSystem.BLL.Users.ColumnNames.RoleID))
                    editUser.Role = user.RoleID;
                if (!user.IsColumnNull(POSSystem.BLL.Users.ColumnNames.UserName))
                    editUser.UserName = user.UserName;
                if (!user.IsColumnNull(POSSystem.BLL.Users.ColumnNames.Address))
                    editUser.Address = user.Address;
                if (!user.IsColumnNull(POSSystem.BLL.Users.ColumnNames.FullName))
                    editUser.FullName = user.FullName;
                if (!user.IsColumnNull(POSSystem.BLL.Users.ColumnNames.Phone))
                    editUser.Phone = user.Phone;
                if (!user.IsColumnNull(POSSystem.BLL.Users.ColumnNames.Password))
                    editUser.Password = user.Password;
            }
            catch (Exception ex)
            {
                ((Popup)Master).ShowErrorMessage(ex.Message);
                ErrorLog.WriteToFile("editUser.aspx.cs", "LoadInfo", ex.StackTrace);
            }
        }

        public void btnSaveAndClose_OnClick(Object sender, EventArgs e)
        {
            if (Save())
                CloseDlg(1);
        }
    }
}
